{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 2.3 自动求梯度\n",
    "\n",
    "在深度学习中，我们经常需要对函数求梯度（gradient）。PyTorch提供的[autograd](https://pytorch.org/docs/stable/autograd.html)包能够根据输入和前向传播过程自动构建计算图，并执行反向传播。本节将介绍如何使用autograd包来进行自动求梯度的有关操作。\n",
    "\n",
    "## 2.3.1 Tensor requires_grad\n",
    "只要将Tensor类，设置为requires_grad 就可以追踪梯度，正向传播完毕后，调用.backward()计算梯度。\n",
    "梯度存在tensor.grad"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch as tf\n",
    "# just joke\n",
    "\n",
    "import torch as t\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意在`y.backward()`时，如果`y`是标量，则不需要为`backward()`传入任何参数；否则，需要传入一个与`y`同形的`Tensor`。\n",
    "\n",
    "如果不想要被继续追踪，可以调用 **`.detach()`** 将其从追踪记录中分离出来，这样就可以防止将来的计算被追踪，这样梯度就传不过去了。此外，还可以用`with torch.no_grad()`将不想被追踪的操作代码块包裹起来，这种方法在评估模型的时候很常用，因为在评估模型时，我们并不需要计算可训练参数（`requires_grad=True`）的梯度。\n",
    "\n",
    "\n",
    "`Function`是另外一个很重要的类。`Tensor`和`Function`互相结合就可以构建一个记录有整个计算过程的有向无环图（DAG）。每个`Tensor`都有一个`.grad_fn`属性，该属性即创建该`Tensor`的`Function`, 就是说该`Tensor`是不是通过某些运算得到的，若是，则`grad_fn`返回一个与这些运算相关的对象，否则是None。\n",
    "\n",
    "## 2.3.2 `Tensor`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[1., 1., 1.],\n",
      "        [1., 1., 1.],\n",
      "        [1., 1., 1.]], requires_grad=True)\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "x = t.ones(3,3, requires_grad = True)\n",
    "print(x)\n",
    "print(x.grad)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[3., 3., 3.],\n",
      "        [3., 3., 3.],\n",
      "        [3., 3., 3.]], grad_fn=<AddBackward0>)\n",
      "True False\n"
     ]
    }
   ],
   "source": [
    "y = x + 2\n",
    "print(y)\n",
    "\n",
    "print(x.is_leaf, y.is_leaf)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意x是直接创建的，所以它没有`grad_fn`, 而y是通过一个加法操作创建的，所以它有一个为`<AddBackward>`的`grad_fn`。\n",
    "像x这种直接创建的称为叶子节点，叶子节点对应的`grad_fn`是`None`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[27., 27., 27.],\n",
      "        [27., 27., 27.],\n",
      "        [27., 27., 27.]], grad_fn=<MulBackward0>) tensor(27., grad_fn=<MeanBackward0>)\n"
     ]
    }
   ],
   "source": [
    "z = (y**2) *3\n",
    "out = z.mean()\n",
    "print(z, out)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "通过`.requires_grad_()`来用in-place的方式改变`requires_grad`属性："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n",
      "tensor(134.8992, grad_fn=<SumBackward0>)\n"
     ]
    }
   ],
   "source": [
    "a = t.randn(3,3)\n",
    "a = a*3 / (a - 1)\n",
    "print(a.requires_grad)\n",
    "a.requires_grad_(True)\n",
    "print(a.requires_grad)\n",
    "b = (a**2).sum()\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.3.2 梯度\n",
    "\n",
    "因为`out`是一个标量，所以调用`backward()`时不需要指定求导变量：\n",
    "\n",
    "```python\n",
    "out.backward() # 等价于 out.backward(torch.tensor(1.))\n",
    "```\n",
    "\n",
    "我们来看看`out`关于`x`的梯度 $\\frac{d(out)}{dx}$:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n"
     ]
    }
   ],
   "source": [
    "print(x.grad)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[2., 2., 2.],\n",
      "        [2., 2., 2.],\n",
      "        [2., 2., 2.]])\n"
     ]
    }
   ],
   "source": [
    "# backward一下\n",
    "out.backward()\n",
    "print(x.grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "我们令`out`为 $o$ , 因为\n",
    "$$\n",
    "o=\\frac19 \\sum_{i=1}^9 z_i=\\frac19\\sum_{i=1}^93(x_i+2)^2\n",
    "$$\n",
    "所以\n",
    "$$\n",
    "\\frac{\\partial{o}}{\\partial{x_i}}\\bigr\\rvert_{x_i=1}=\\frac{9\\times2}{9}=2\n",
    "$$\n",
    "\n",
    "数学上，如果有一个函数值和自变量都为向量的函数 $\\vec{y}=f(\\vec{x})$, 那么 $\\vec{y}$ 关于 $\\vec{x}$ 的梯度就是一个雅可比矩阵（Jacobian matrix）:\n",
    "$$\n",
    "J=\\left(\\begin{array}{ccc}\n",
    "   \\frac{\\partial y_{1}}{\\partial x_{1}} & \\cdots & \\frac{\\partial y_{1}}{\\partial x_{n}}\\\\\n",
    "   \\vdots & \\ddots & \\vdots\\\\\n",
    "   \\frac{\\partial y_{m}}{\\partial x_{1}} & \\cdots & \\frac{\\partial y_{m}}{\\partial x_{n}}\n",
    "   \\end{array}\\right)\n",
    "$$\n",
    "而``torch.autograd``这个包就是用来计算一些雅克比矩阵的乘积的。例如，如果 $v$ 是一个标量函数的 $l=g\\left(\\vec{y}\\right)$ 的梯度：\n",
    "$$\n",
    "v=\\left(\\begin{array}{ccc}\\frac{\\partial l}{\\partial y_{1}} & \\cdots & \\frac{\\partial l}{\\partial y_{m}}\\end{array}\\right)\n",
    "$$\n",
    "那么根据链式法则我们有 $l$ 关于 $\\vec{x}$ 的雅克比矩阵就为:\n",
    "$$\n",
    "v J=\\left(\\begin{array}{ccc}\\frac{\\partial l}{\\partial y_{1}} & \\cdots & \\frac{\\partial l}{\\partial y_{m}}\\end{array}\\right) \\left(\\begin{array}{ccc}\n",
    "   \\frac{\\partial y_{1}}{\\partial x_{1}} & \\cdots & \\frac{\\partial y_{1}}{\\partial x_{n}}\\\\\n",
    "   \\vdots & \\ddots & \\vdots\\\\\n",
    "   \\frac{\\partial y_{m}}{\\partial x_{1}} & \\cdots & \\frac{\\partial y_{m}}{\\partial x_{n}}\n",
    "   \\end{array}\\right)=\\left(\\begin{array}{ccc}\\frac{\\partial l}{\\partial x_{1}} & \\cdots & \\frac{\\partial l}{\\partial x_{n}}\\end{array}\\right)\n",
    "$$\n",
    "注意：grad在反向传播过程中是累加的(accumulated)，这意味着每一次运行反向传播，梯度都会累加之前的梯度，所以一般在反向传播之前需把梯度清零"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[1., 1., 1.],\n",
      "        [1., 1., 1.],\n",
      "        [1., 1., 1.]], requires_grad=True)\n",
      "tensor(9., grad_fn=<SumBackward0>)\n",
      "tensor([[3., 3., 3.],\n",
      "        [3., 3., 3.],\n",
      "        [3., 3., 3.]])\n",
      "tensor([[1., 1., 1.],\n",
      "        [1., 1., 1.],\n",
      "        [1., 1., 1.]])\n"
     ]
    }
   ],
   "source": [
    "out2 = x.sum()\n",
    "print(x)\n",
    "print(out2)\n",
    "\n",
    "out2.backward()\n",
    "print(x.grad)\n",
    "\n",
    "out3 = x.sum()\n",
    "x.grad.data.zero_()\n",
    "out3.backward()\n",
    "print(x.grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " > 现在我们解释2.3.1节留下的问题，为什么在`y.backward()`时，如果`y`是标量，则不需要为`backward()`传入任何参数；否则，需要传入一个与`y`同形的`Tensor`?\n",
    "简单来说就是为了避免向量（甚至更高维张量）对张量求导，而转换成标量对张量求导。举个例子，假设形状为 `m x n` 的矩阵 X 经过运算得到了 `p x q` 的矩阵 Y，Y 又经过运算得到了 `s x t` 的矩阵 Z。那么按照前面讲的规则，dZ/dY 应该是一个 `s x t x p x q` 四维张量，dY/dX 是一个 `p x q x m x n`的四维张量。问题来了，怎样反向传播？怎样将两个四维张量相乘？？？这要怎么乘？？？就算能解决两个四维张量怎么乘的问题，四维和三维的张量又怎么乘？导数的导数又怎么求，这一连串的问题，感觉要疯掉…… "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 为了避免这个问题，我们**不允许张量对张量求导，只允许标量对张量求导，求导结果是和自变量同形的张量**。所以必要时我们要把张量通过将所有张量的元素加权求和的方式转换为标量，举个例子，假设`y`由自变量`x`计算而来，`w`是和`y`同形的张量，则`y.backward(w)`的含义是：先计算`l = torch.sum(y * w)`，则`l`是个标量，然后求`l`对自变量`x`的导数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[2., 4.],\n",
      "        [6., 8.]], grad_fn=<ViewBackward>)\n",
      "tensor([2.0000, 0.2000, 0.0200, 0.0020])\n",
      "tensor([[2., 4.],\n",
      "        [6., 8.]], grad_fn=<ViewBackward>)\n",
      "tensor([2.0000, 0.2000, 0.0200, 0.0020])\n",
      "tensor([2., 4., 6., 8.], grad_fn=<MulBackward0>) tensor(20., grad_fn=<SumBackward0>)\n",
      "tensor([2., 2., 2., 2.])\n"
     ]
    }
   ],
   "source": [
    "x = t.tensor([1.0,2,3,4], requires_grad = True)\n",
    "y = x*2\n",
    "z = y.view(2,-1)\n",
    "print(z)#现在 `z` 不是一个标量，所以在调用`backward`时需要传入一个和`z`同形的权重向量进行加权求和得到一个标量。\n",
    "#回传一个v\n",
    "v= t.tensor([[1.0,0.1],[0.01,0.001]], dtype = t.float)\n",
    "z.backward(v)\n",
    "print(x.grad)\n",
    "\n",
    "\n",
    "#相当于是 计算l = torch.sum(y * w) l为标量，然后在计算l.backward\n",
    "#一般loss.sum() 也是这个原因吧，只能计算标量对张量求导\n",
    "x = t.tensor([1.0,2,3,4], requires_grad = True)\n",
    "y = x*2\n",
    "z = y.view(2,-1)\n",
    "print(z)\n",
    "\n",
    "v= t.tensor([1.0,0.1,0.01,0.001], dtype = t.float)\n",
    "#与上面the sam\n",
    "l = t.sum(y*v)\n",
    "l.backward()\n",
    "print(x.grad)\n",
    "\n",
    "\n",
    "# dz/dx = 2 所以x.grad = [2 2 2 2]\n",
    "\n",
    "x = t.tensor([1.0,2,3,4], requires_grad = True)\n",
    "y = x*2\n",
    "z = y.sum()\n",
    "print(y, z)\n",
    "z.backward()\n",
    "print(x.grad)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一个重要的知识点：\n",
    "**注意，`x.grad`是和`x`同形的张量。**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "tensor(1., grad_fn=<PowBackward0>) True\n",
      "tensor(1.) False\n",
      "tensor(2., grad_fn=<AddBackward0>) True\n"
     ]
    }
   ],
   "source": [
    "x = t.tensor(1.0, requires_grad=True)\n",
    "y1 = x ** 2 \n",
    "with t.no_grad():\n",
    "    y2 = x ** 3\n",
    "y3 = y1 + y2\n",
    "    \n",
    "print(x.requires_grad)\n",
    "print(y1, y1.requires_grad) # True\n",
    "print(y2, y2.requires_grad) # False\n",
    "print(y3, y3.requires_grad) # True"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以看到，上面的`y2`是没有`grad_fn`而且`y2.requires_grad=False`的，而`y3`是有`grad_fn`的。如果我们将`y3`对`x`求梯度的话会是多少呢？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(2.)\n"
     ]
    }
   ],
   "source": [
    "y3.backward()\n",
    "print(x.grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为什么是2呢？$ y_3 = y_1 + y_2 = x^2 + x^3$，当 $x=1$ 时 $\\frac {dy_3} {dx}$ 不应该是5吗？事实上，由于 $y_2$ 的定义是被`torch.no_grad():`包裹的，所以与 $y_2$ 有关的梯度是不会回传的，只有与 $y_1$ 有关的梯度才会回传，即 $x^2$ 对 $x$ 的梯度。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "此外，如果我们想要修改`tensor`的数值，但是又不希望被`autograd`记录（即不会影响反向传播），那么我么可以对`tensor.data`进行操作。\n",
    "如果仅仅是想取出来用一下，但是不包括在计算图内，则可以`.data`方法\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([1.])\n",
      "False\n",
      "tensor([100.], requires_grad=True)\n",
      "tensor([2.])\n"
     ]
    }
   ],
   "source": [
    "x = t.ones(1,requires_grad=True)\n",
    "\n",
    "print(x.data) # 还是一个tensor\n",
    "print(x.data.requires_grad) # 但是已经是独立于计算图之外\n",
    "\n",
    "y = 2 * x\n",
    "x.data *= 100 # 只改变了值，不会记录在计算图，所以不会影响梯度传播\n",
    "\n",
    "y.backward()\n",
    "print(x) # 更改data的值也会影响tensor的值\n",
    "print(x.grad)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
